(function () {
    "use strict";
    const username = document.querySelector('.username'),
        spanusername = document.querySelector('.spanusername'),
        man = document.querySelector('#man'),
        woman = document.querySelector('#woman'),
        spansex = document.querySelector('.spansex'),
        useremail = document.querySelector('.useremail'),
        spanuseremail = document.querySelector('.spanuseremail'),
        userphone = document.querySelector('.userphone'),
        spanuserphone = document.querySelector('.spanuserphone'),
        userdepartment = document.querySelector('.userdepartment'),
        spanuserdepartment = document.querySelector('.spanuserdepartment'),
        userjob = document.querySelector('.userjob'),
        spanuserjob = document.querySelector('.spanuserjob'),
        userdesc = document.querySelector('.userdesc'),
        spanuserdesc = document.querySelector('.spanuserdesc'),
        submit = document.querySelector('.submit');

    // 获取问号传参信息
    let { userId } = Qs.parse(location.search.replace('?', ''));

    // 绑定部门信息 && 绑定职务信息
    const bindDepartment = async () => {
        let departList = await api.queryDepartmentList();
        let str = ``;
        departList.forEach(item => {
            str += `<option value="${item.id}">
                ${item.name}
            </option>`;
        });
        userdepartment.innerHTML = str;
    };
    const bindJob = async () => {
        let jobList = await api.queryJobList();
        let str = ``;
        jobList.forEach(item => {
            str += `<option value="${item.id}">
                ${item.name}
            </option>`;
        });
        userjob.innerHTML = str;
    };
    Promise.all([bindDepartment(), bindJob()])
        .then(() => {
            if (!userId) return Promise.reject();
            return http.get('/user/info', {
                params: {
                    userId
                }
            });
        })
        .then(value => {
            let { code, info } = value;
            if (+code === 1) return;
            username.value = info.name;
            +info.sex === 0 ? man.checked = true : woman.checked = true;
            useremail.value = info.email;
            userphone.value = info.phone;
            userdepartment.value = info.departmentId;
            userjob.value = info.jobId;
            userdesc.value = info.desc;
        })
        .catch(() => { });

    // 表单校验
    const validate = {
        username() {
            let text = username.value.trim();
            if (text.length === 0) {
                spanusername.innerHTML = '用户名不能为空!';
                return false;
            }
            if (!/^(?:[\u4e00-\u9fa5·]{2,16})$/.test(text)) {
                spanusername.innerHTML = '用户名格式不正确!';
                return false;
            }
            spanusername.innerHTML = '';
            return true;
        },
        useremail() {
            let text = useremail.value.trim(),
                reg = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            if (text.length === 0) {
                spanuseremail.innerHTML = '邮箱不能为空!';
                return false;
            }
            if (!reg.test(text)) {
                spanuseremail.innerHTML = '邮箱格式不正确!';
                return false;
            }
            spanuseremail.innerHTML = '';
            return true;
        },
        userphone() {
            let text = userphone.value.trim(),
                reg = /^(?:(?:\+|00)86)?1\d{10}$/;
            if (text.length === 0) {
                spanuserphone.innerHTML = '手机号不能为空!';
                return false;
            }
            if (!reg.test(text)) {
                spanuserphone.innerHTML = '手机号格式不正确!';
                return false;
            }
            spanuserphone.innerHTML = '';
            return true;
        },
        userdesc() {
            let text = userdesc.value.trim();
            if (text.length > 500) {
                spanuserdesc.innerHTML = '最多输入500个文字!';
                return false;
            }
            spanuserdesc.innerHTML = '';
            return true;
        },
        userdepartment() {
            let val = userdepartment.value;
            if (val.length === 0) {
                spanuserdepartment.innerHTML = '请选择部门~';
                return false;
            }
            spanuserdepartment.innerHTML = '';
            return true;
        },
        userjob() {
            let val = userjob.value;
            if (val.length === 0) {
                spanuserjob.innerHTML = '请选择职务~';
                return false;
            }
            spanuserjob.innerHTML = '';
            return true;
        }
    };
    username.onblur = validate.username;
    useremail.onblur = validate.useremail;
    userphone.onblur = validate.userphone;
    userdesc.onblur = validate.userdesc;

    // 表单提交
    let isRun;
    submit.onclick = async function () {
        if (!validate.username() || !validate.useremail() || !validate.userphone() || !validate.userdesc() || !validate.userdepartment() || !validate.userjob()) return;
        let data = {
            name: username.value.trim(),
            sex: man.checked ? 0 : 1,
            email: useremail.value.trim(),
            phone: userphone.value.trim(),
            departmentId: userdepartment.value,
            jobId: userjob.value,
            desc: userdesc.value
        };
        let url = '/user/add';
        if (userId) {
            // 修改
            data.userId = userId;
            url = '/user/update';
        }

        if (isRun) return;
        isRun = true;
        submit.style.background = '#DDD';
        try {
            let { code } = await http.post(url, data);
            if (+code === 0) {
                isRun = false;
                submit.style.background = '#2299EE';
                alert('恭喜您，操作成功!');
                window.parent.location.hash = 'userlist';
                location.href = 'userlist.html';
                return;
            }
        } catch (_) { }
        alert('操作失败，请稍后再试!');
        isRun = false;
        submit.style.background = '#2299EE';
    };
})();